package com.itheima.config;


import com.itheima.security.HealthUserDetailServiceImpl;
import com.itheima.security.JWTAuthenticationFilter;
import com.itheima.security.JWTAuthorizationFilter;
import com.itheima.security.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启权限注解
//将JwtProperties类创建并扔到ioc容器中
@EnableConfigurationProperties(JwtProperties.class)
public class HealthWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private HealthUserDetailServiceImpl healthUserDetailService;

    @Autowired
    private JwtProperties properties;//注入jwt需要的公钥私钥

    /**
     * {noop}明文密码效验
     * 重写权限认证信息
     * @param auth
     * @throws Exception
     * 密码加密 框架 PasswordEncoder密码加密
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库版认证和授权配置
        auth.userDetailsService(healthUserDetailService).passwordEncoder(createdPasswordEncoder());

    }

    /**
     * 创建PasswordEncoder密码加密对象并放入ioc容器中
     * @return密码加密 对象
     * BCryptPasswordEncoder是PasswordEncoder实现子类
     */
    @Bean
    public PasswordEncoder createdPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().
                disable().//crsf 禁用
                //addFilter添加自定义过滤器
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(),properties))
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),properties))
                //分布式不采用session，我们禁用掉他
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session
    }


}
